<?php

namespace app\common\model\banxi\learn;

use app\common\enums\LearnMeansEnum;
use app\common\enums\ReadingTypeEnum;
use app\common\model\banxi\course\Course;
use app\common\model\banxi\student\Student;
use app\common\model\common\BaseModel;
use app\common\service\DouBaoAiArticleService;
use app\common\service\queue\QueueService;
use app\common\service\TencentVocalService;
use think\model\concern\SoftDelete;

/**
 * 阅读理解文章记录
 */
class LearnReadingArticle extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_reading_article';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'readingTypeCn',
        'learnMeansCn',
        'actualCourseIdList',
        'useTimeMs',
        'actualCourseList'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'skRecordId' => 'string',
        'studentId' => 'string',
        'trainerId' => 'string',
        'isSubmit' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getReadingTypeCnAttr($value,$data): string
    {
        $value = $value ?: ($data['readingType'] ?? '');
        return (new ReadingTypeEnum())->getDescription($value) ?? '';
    }

    public function getLearnMeansCnAttr($value,$data): string
    {
        $value = $value ?: ($data['learnMeans'] ?? '');
        return (new LearnMeansEnum())->getDescription($value) ?? '';
    }


    public function getActualCourseIdListAttr($value,$data): array
    {
        return explode(',', $data['actualCourseId']);
    }

    public function getUseTimeMsAttr($value,$data): string
    {
        return secondToTime($data['useTime']);
    }

    public function getActualCourseListAttr($value,$data)
    {
        return Course::whereIn('id', $data['actualCourseId'])->field('id,name')->select();
    }


    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    /**
     * 获取同一个上课记录下的答题次数
     * @param $skRecordId 上课记录
     * @param $articleId 文章关卡
     */
    public function countAnswerBySkRecordAndArticleId($skRecordId, $articleId)
    {
        $count = self::where(['skRecordId' => $skRecordId, 'articleId' => $articleId, 'readingType' => 2, 'isSubmit' => 1])->count();
        return $count;
    }


    /*
     * 开始AI阅读
     * */
    public function startAiReading($skRecordId, $trainerId, $words)
    {
        $studentId = 0;
        $learnMeans = 2;
        if ($skRecordId) {
            $LearnSkRecordModel = new LearnSkRecord();
            $learnSkRecord = $LearnSkRecordModel->where(['id' => $skRecordId])->find();
            if (!$learnSkRecord) {
                getResponseException('上课记录不存在', [], 1, 'ERROR');
            }
            if ($learnSkRecord['trainerId'] != $trainerId) {
                getResponseException('上课记录不存在', [], 1, 'ERROR');
            }
            $studentId = $learnSkRecord['studentId'];
            $learnMeans = 1;
        }

        return $this->handleAiArticle($skRecordId, $studentId, $trainerId, $words, $learnMeans);
    }

    /*
     * 处理AI文章
     * */
    public function handleAiArticle($skRecordId, $studentId, $trainerId, $words, $learnMeans)
    {
        $studentOrgId = 0;
        if ($studentId) {
            $Student = new Student();
            $student = $Student->where(['id' => $studentId])->find();
            if (!$student) {
                getResponseException('学员不存在', [], 1, 'ERROR');
            }
            $studentOrgId = $student['organizationId'];
        }

        if (count($words) > 10) {
            getResponseException('单词不能超过10个', [], 1, 'ERROR');
        }
        $WordSetRaw = $this->extractCourseIdAndWordSetRaw($words);
        $courseIdSet = $WordSetRaw['courseIdSet'];
        $wordSet = $WordSetRaw['wordSet'];
        //        halt($WordSetRaw);
        // 生成AI文章
        $DouBaoAiArticleService = new DouBaoAiArticleService();
        $articleNewByWords = $DouBaoAiArticleService->getArticleNewByWords(implode(',', $wordSet));
        //        $articleNewByWords = [
        //            "titleEn" => "Would You Go to the Zoo with Me?",
        //            "titleCh"=> "你愿意和我一起去动物园吗？",
        //            "paragraphs"=> [
        //                [
        //                    "en"=> "It was a bright sunny Saturday morning. I jumped out of bed, eager to spend the day with my friend. I grabbed my phone and dialed Lucy’s number. “Hi Lucy! The weather is perfect—would you like to go to the zoo with me today?” I asked, my voice brimming with excitement.",
        //                    "cn"=> "那是一个阳光明媚的星期六早晨。我从床上跳起来，渴望和朋友一起度过这一天。我抓起手机拨通了露西的号码。“嗨，露西！天气太棒了——你今天愿意和我一起去动物园吗？”我问道，声音里充满了兴奋。"
        //                ],
        //                [
        //                    "en"=> "Lucy’s reply came quickly, full of joy. “Yes! I’ve been wanting to see the new pandas,” she said. We met at the zoo entrance fifteen minutes later, each carrying a bag of popcorn. As we walked in, the sound of birds chirping and children laughing filled the air.",
        //                    "cn"=> "露西的回复来得很快，充满了喜悦。“愿意！我一直想看新到的熊猫，”她说。十五分钟后我们在动物园入口见面，每个人都带着一袋爆米花。当我们走进来时，空气中充满了鸟叫声和孩子们的笑声。"
        //                ],
        //                [
        //                    "en"=> "We spent the afternoon exploring: watching lions lounge in the sun, giraffes stretch their long necks to eat leaves, and penguins waddle in their icy enclosure. The highlight was feeding the rabbits—one fluffy brown rabbit hopped to Lucy, and she held out a carrot. It nibbled gently, and she giggled. “Look, it likes you!” I said, pointing to the rabbit.",
        //                    "cn"=> "我们花了整个下午探索：看狮子在阳光下躺着，长颈鹿伸长脖子吃叶子，企鹅在冰冷的围栏里蹒跚而行。最精彩的是喂兔子——一只毛茸茸的棕色兔子跳到露西身边，她拿出一根胡萝卜。兔子轻轻啃着，她笑了。“看，它喜欢你！”我指着兔子说。"
        //                ],
        //               [
        //                    "en"=> "As the day came to an end, we sat on a bench, tired but happy. “Thank you for inviting me,” Lucy said. “I had so much fun at the zoo.” I smiled and replied, “Me too! Would you want to come again next weekend?” She nodded, her eyes shining. “Absolutely!”",
        //                    "cn"=> "当一天即将结束时，我们坐在长椅上，虽然累但很开心。“谢谢你邀请我，”露西说。“我在动物园玩得很开心。”我笑着回答：“我也是！你下周末想再来吗？”她点点头，眼睛发亮。“当然！”"
        //                ]
        //            ]
        //        ];
        //        halt($articleNewByWords);
        // 保存开始阅读记录
        $learnReadingArticle = $this->create([
            'skRecordId' => $skRecordId,
            'studentId' => $studentId,
            'studentOrgId' => $studentOrgId,
            'actualCourseId' => implode(',', $courseIdSet),
            'trainerId' => $trainerId,
            'articleName' => $articleNewByWords['titleEn'],
            'startTime' => date('Y-m-d H:i:s', time()),
            'learnMeans' => $learnMeans,
            'limitAnswer' => 0,
            'readingType' => 1
        ]);
        $readingArticleId = $learnReadingArticle->id;

        // 保存扩展记录
        $LearnReadingArticleExtendModel = new LearnReadingArticleExtend();
        $articleContent = $this->getArticleContentEnAttr($articleNewByWords);
        $articleContentCn = $this->getArticleContentCnAttr($articleNewByWords);
        $articleContentParagraph = $this->getArticleParagraphEn($articleNewByWords['paragraphs']);
        $articleContentCaragraphCn = $this->getArticleParagraphCn($articleNewByWords['paragraphs']);
        //生成文章音频
        $tencentVocalService = new TencentVocalService();
        $ttlTaskId = $tencentVocalService->longTextToVoiceTheStandardAndEn($articleContent, '/common_api/CallBack/aiArticlettlCallback?server=1');
        //        $ttlTaskId = '123123123';
        //        halt($ttlTaskId);
        $articleExtend = $LearnReadingArticleExtendModel->create([
            'readingArticleId' => $readingArticleId,
            'articleTitle' => $articleNewByWords['titleEn'],
            'articleTitleCn' => $articleNewByWords['titleCh'],
            'articleContent' => $articleContent,
            'articleContentCn' => $articleContentCn,
            'articleContentParagraph' => $articleContentParagraph,
            'articleContentCaragraphCn' => $articleContentCaragraphCn,
            'articleWordNum' => $this->getArticleWordNum($articleContent),
            'ttlTaskId' => $ttlTaskId
        ]);
        $readingArticleExtendId = $articleExtend->id;

        $QueueService = new QueueService();
        //生成文章题目信息
        $QueueService->getAiArticleQuestionJob([
            'readingArticleId' => $readingArticleId,
            'studentId' => $studentId,
            'trainerId' => $trainerId,
            'articleContent' => $articleContent,
            'readingArticleExtendId' => $readingArticleExtendId
        ]);
        //生成文章短句
        $QueueService->getArticleSentenceByContentJob([
            'articleContent' => $articleContent,
            'readingArticleExtendId' => $readingArticleExtendId
        ]);
        //生成文章核心词汇
        $QueueService->getArticleWordByContent([
            'articleContent' => $articleContent,
            'readingArticleExtendId' => $readingArticleExtendId
        ]);
        //生成文章时态
        $QueueService->getArticleParagraphByContent([
            'articleContent' => $articleContent,
            'readingArticleExtendId' => $readingArticleExtendId
        ]);
        //生成文章句子结构
        $QueueService->getArticleSentenceStructureByContent([
            'articleContent' => $articleContent,
            'readingArticleExtendId' => $readingArticleExtendId
        ]);

        return $readingArticleId;
    }

    /**
     * 获取文章英文内容
     *
     * @param mixed $value
     * @param array $data
     * @return string
     */
    public function getArticleContentEnAttr($data)
    {
        if (!isset($data['paragraphs']) || empty($data['paragraphs'])) {
            return '';
        }

        $paragraphs = is_string($data['paragraphs']) ? json_decode($data['paragraphs'], true) : $data['paragraphs'];
        $content = '';

        foreach ($paragraphs as $paragraph) {
            $content .= ($paragraph['en'] ?? '') . "\n";
        }

        return $content;
    }

    /**
     * 获取文章中文内容
     *
     * @param mixed $value
     * @param array $data
     * @return string
     */
    public function getArticleContentCnAttr($data)
    {
        if (!isset($data['paragraphs']) || empty($data['paragraphs'])) {
            return '';
        }

        $paragraphs = is_string($data['paragraphs']) ? json_decode($data['paragraphs'], true) : $data['paragraphs'];
        $content = '';

        foreach ($paragraphs as $paragraph) {
            $content .= ($paragraph['cn'] ?? '') . "\n";
        }

        return $content;
    }

    /**
     * 获取文章段落英文内容（用分隔符连接）
     *
     * @param array $paragraphs 段落列表
     * @return string
     */
    public function getArticleParagraphEn($paragraphs)
    {
        if (empty($paragraphs)) {
            return '';
        }

        // 提取所有段落的英文内容
        $paragraphEnList = array_map(function ($paragraph) {
            if (is_array($paragraph)) {
                return $paragraph['en'] ?? '';
            } else {
                return $paragraph->en ?? '';
            }
        }, $paragraphs);

        // 用分隔符连接
        return implode('|', $paragraphEnList);
    }

    /**
     * 获取文章段落中文内容（用分隔符连接）
     *
     * @param array $paragraphs 段落列表
     * @return string
     */
    public function getArticleParagraphCn($paragraphs)
    {
        if (empty($paragraphs)) {
            return '';
        }

        // 提取所有段落的中文内容
        $paragraphCnList = array_map(function ($paragraph) {
            if (is_array($paragraph)) {
                return $paragraph['cn'] ?? '';
            } else {
                return $paragraph->cn ?? '';
            }
        }, $paragraphs);

        // 用分隔符连接
        return implode('|', $paragraphCnList);
    }

    /**
     * 获取文章单词数量
     *
     * @param string $content 文章内容
     * @return int 单词数量
     */
    public function getArticleWordNum(string $content): int
    {
        if (empty($content)) {
            return 0;
        }

        // 移除多余的空白字符，只保留单个空格
        $content = preg_replace('/\s+/', ' ', trim($content));

        if (empty($content)) {
            return 0;
        }

        // 按空格分割单词并计算数量
        $words = explode(' ', $content);
        return count($words);
    }

    /**
     * 从单词列表中提取课程ID集合和单词集合
     *
     * @param array $words 单词列表
     * @return array ['courseIdSet' => [], 'wordSet' => []]
     */
    public function extractCourseIdAndWordSetRaw(array $words): array
    {
        if (empty($words)) {
            return ['courseIdSet' => [], 'wordSet' => []];
        }

        // 提取课程ID和单词
        $courseIds = array_column($words, 'courseId');
        $wordsList = array_column($words, 'word');

        // 去重处理
        $courseIdSet = array_values(array_unique($courseIds));
        $wordSet = array_values(array_unique($wordsList));

        return [
            'courseIdSet' => $courseIdSet,
            'wordSet' => $wordSet
        ];
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function studentInfo()
    {
        return $this->hasOne(Student::class, 'id', 'studentId');
    }

}